﻿// event handler
function init() {
	
	console.log('init');


	/*
	 * global variables
	 */ 	
	//request = new XMLHttpRequest();
	URL_MESSAGE = "/demo3/api/message";
	URL_USER = "/demo3/api/user";
	username = 'noname';
	sizeListMessage = 0;
	
	mapEmoticon = [ {
		emoticon : ":))",
		image : "<img src='icon/emoticon-3-icon.png'>"
	}, {
		emoticon : ":)",
		image : "<img src='icon/emoticons-icon.png'>"
	}, {
		emoticon : ":P",
		image : "<img src='icon/emoticon-2-icon.png'>"
	}

	];
	
	fontFamily = 'Arial';
	fontSize = '12px';
	fontColor = '#000000';
	/*
	 * html page
	 */ 
	htmlPage = document.body;
	/*
	 * login div
	 */ 
	loginForm = document.getElementById('login-form');
	inputUsername = document.getElementById('input-username');
	inputPassword = document.getElementById('input-password');
	btnLogin = document.getElementById('btnLogin');
	lblError = document.getElementById('lblError');
	/*
	 * content div
	 */ 
	chatForm = document.getElementById('content');
	textMenu = document.getElementById('text-menu');
	emoticonMenu = document.getElementById('emoticon-menu');
	chatArea = document.getElementById('chat-area');
	btnSend = document.getElementById('btnSend');
	btnQuit = document.getElementById('btnQuit');
	pMessageArea = document.getElementById('iframe-message-area');
	pMessageArea.contentEditable = true;
	pMessageArea.style.color = fontColor;
	pMessageArea.style.fontFamily = fontFamily;
	pMessageArea.style.fontSize = fontSize;
	// popup text
	popupMenuText = document.getElementById('popup-menu-text');
	selectFont = document.getElementById('select-font');
	selectFontSize = document.getElementById('select-font-size');
	selectColor = document.getElementById('select-color');
	// popup emoticon
	popupMenuEmoticon = document.getElementById('popup-menu-emoticon');
	// avatar panel
	imgAvatar = document.getElementById('avatar1');
	roomInfoArea = document.getElementById('room-info');
	/*
	 * event binding
	 */ 
	// menu
	textMenu.onclick =function(event){
		showTextMenu(event);
	};
	emoticonMenu.onclick = function(event){
		showEmoticonMenu(event);
	};
	popupMenuText.onclick = function(event) {
		event.stopPropagation();
	};
	//button
	btnSend.onclick = sendMessage; 
	btnLogin.onclick = function() {
		login(loginSuccess);
	};
	btnQuit.onclick = function() {
		quit();
		location.reload(true);
	};
	//emoticon
	for ( var i = 0; i < 3; i++) {
		document.getElementById('emo' + (i + 1)).onclick = makeAppendEmoticonCallback(i);
	}
	// input text
	inputUsername.focus();
	inputUsername.onkeyup = function(event){
		 enterForLogin(event);
	};	
	inputPassword.onkeyup = function(event){
		 enterForLogin(event);
	};	
	pMessageArea.onkeyup = function(event) {
		enterPressed(event);
	};
	// body
	htmlPage.onclick = hideAllPopup;
	//select 
	selectFont.onchange = changeFontFamily;	
	selectFontSize.onchange = changeFontSize;
	selectColor.onchange = changeColor;
	selectColor.onclick = function() {
		selectColor.color.showPicker();	
	};
	// refresh page or close tab
	window.onunload = quit;
	window.onbeforeunload = quit;	
	
}

/*
 * group popup menu function
 */
function showTextMenu(event) {
	
	if (popupMenuText.style.visibility == 'hidden') {
		popupMenuText.style.visibility = 'visible';
		
		
	} else {
		popupMenuText.style.visibility = 'hidden';
		console.log(popupMenuText.getAttribute('style'));
	}
	event.stopPropagation();
}

function showEmoticonMenu(event) {
	if (popupMenuEmoticon.style.visibility == 'hidden') {
		popupMenuEmoticon.style.visibility = 'visible';

	} else {
		popupMenuEmoticon.style.visibility = 'hidden';		
	}
	event.stopPropagation();
}

function makeAppendEmoticonCallback(id) {
	return function() {
		appendEmoticon(id);
	};
}

function appendEmoticon(id) {
	pMessageArea.innerHTML = pMessageArea.innerHTML.concat(mapEmoticon[id].emoticon);
	popupMenuEmoticon.style.visibility = 'hidden';
}

function hideAllPopup(){
	console.log("click vao element");
	popupMenuText.style.visibility = 'hidden';
	popupMenuEmoticon.style.visibility = 'hidden';
}
/*
 * group message function
 */
function checkListMessages(getListMessages) {
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200){// If it was successful
				var size = parseInt(request.responseText);
				if(sizeListMessage != size)
					getListMessages(updateChatArea);
				
			} 
				
		}
	};
	request.open("GET", URL_MESSAGE);
	request.send(null);
}



/*function poll(callback) {
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200){// If it was successful
				//var size = parseInt(request.responseText);
				
				if(request.responseText != ""){
					//getListMessages(updateChatArea);
					var listMessage = JSON.parse(request.responseText);
					//sizeListMessage += listMessage.length;
					//console.log(listMessage);
					callback(listMessage);
				} else {
					console.log("Chua co message moi");
					poll(callback);
				}
					
				
			} 
				
		}
	};
	request.open("GET", URL_MESSAGE+"/"+sizeListMessage);
	request.send(null);
}*/

function poll(callback) {
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200){// If it was successful
				//var size = parseInt(request.responseText);
				
				if(request.responseText != ""){
					//getListMessages(updateChatArea);
					
					var listMessage = JSON.parse(request.responseText);
					//sizeListMessage += listMessage.length;
					console.log(listMessage);
					callback(listMessage);
					
				} else {
					console.log("Chua co message moi");
					
				}
				poll(callback);
				
			} 
				
		}
	};
	/*var data={
			fromIndex : sizeListMessage
	};*/
	request.open("POST", URL_MESSAGE);
	//request.setRequestHeader("Content-Type","application/json;charset=UTF-8");
	//var value = JSON.stringify(data);
	request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	console.log("fromIndex="+sizeListMessage);
	request.send("fromIndex="+sizeListMessage+"&name="+username);

}

function getListMessages(updateChatArea){
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200){// If it was successful
				updateChatArea(JSON.parse(request.responseText));
			} 
				
		}
	};
	request.open("GET", URL_MESSAGE+"/"+sizeListMessage);
	request.send(null);
}

function updateChatArea(listMessage) { // list message json
	sizeListMessage += listMessage.length;
	for ( var i = 0; i < listMessage.length; i++) {		
			var message = listMessage[i];
			var p = document.createElement('p');
			var spanContent = document.createElement('span');
			var spanTime = document.createElement('span');
			var spanUser = document.createElement('span');
			spanContent.innerHTML = message.content;
			spanContent.className = 'content';
			spanContent.style.fontFamily = message.fontFamily; // set font family
			spanContent.style.fontSize = message.fontSize; // set font size
			spanContent.style.color = message.fontColor; // set font color
			addEmoticon(spanContent);

			spanTime.innerHTML = message.time;
			spanTime.className = 'time';
			spanUser.innerHTML = message.name;
			if(message.name == username)
				spanUser.className = 'name';
			else
				spanUser.className = 'other';
			p.appendChild(spanUser);
			p.appendChild(spanContent);
			p.appendChild(spanTime);
			chatArea.appendChild(p);
		}
		chatArea.scrollTop = chatArea.scrollHeight;
}

function clearInterval() {
	clearInterval(timerRequest);
}

function sendMessage(callback) {

	var message = pMessageArea.innerHTML;
	console.log("send message" + message );
	if (message != "") {
		var data = {
			name : username,
			content : message,
			time : getTime(),
			fontFamily: fontFamily,
			fontSize: fontSize,
			fontColor : fontColor
		};
	/*	var p = document.createElement('p');
		var spanContent = document.createElement('span');
		var spanTime = document.createElement('span');
		var spanUser = document.createElement('span');
		spanContent.innerHTML = data.content;
		spanContent.className = 'content';
		spanContent.style.fontFamily = fontFamily; // set font family
		spanContent.style.fontSize = fontSize; // set font size
		spanContent.style.color = fontColor; // set font color
		addEmoticon(spanContent);

		spanTime.innerHTML = data.time;
		spanTime.className = 'time';
		spanUser.innerHTML = data.name;
		spanUser.className = 'name';
		p.appendChild(spanUser);
		p.appendChild(spanContent);
		p.appendChild(spanTime);
		chatArea.appendChild(p);
		// increase size
		sizeListMessage++;*/
		// ajax send message
		var request = new XMLHttpRequest();
		request.onreadystatechange = function() {
			if (request.readyState == 4) { // If the request is finished
				if (request.status == 200) // If it was successful
					console.log("post success");
					//callback(updateChatArea);
			}
		};
		request.open("POST", URL_MESSAGE);
		request.setRequestHeader("Content-Type","application/json;charset=UTF-8");
		var value = JSON.stringify(data);
		console.log("send message json "+ value);
		request.send(value);
		// auto scroll to bottom
		chatArea.scrollTop = chatArea.scrollHeight;
	}

	pMessageArea.innerHTML = "";
	pMessageArea.focus();
}

function enterPressed(event) {
	if (event.keyCode == 13) {
		var listDivBR = pMessageArea.getElementsByTagName("div");// remove
		if (listDivBR.length == 0) {
			listDivBR = pMessageArea.getElementsByTagName("br");
		}

		for ( var i = listDivBR.length - 1; i >= 0; i--) {
			pMessageArea.removeChild(listDivBR[i]);
		}

		sendMessage(poll);
	}
}

function addEmoticon(spanContent) {
	var index = -1;
	for ( var i = 0; i < mapEmoticon.length; i++) {
		index = spanContent.innerHTML.indexOf(mapEmoticon[i].emoticon);
		while (index != -1) {
			spanContent.innerHTML = spanContent.innerHTML.replace(
					mapEmoticon[i].emoticon, mapEmoticon[i].image);
			index = spanContent.innerHTML.indexOf(mapEmoticon[i].emoticon);
		}

	}
}
/*
 * group XmlHttpRequest function
 */
function post(url,data) {
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200) // If it was successful
				console.log("post success");
		}
	};
	request.open("POST", url);
	request.setRequestHeader("Content-Type","application/json;charset=UTF-8");
	var value = JSON.stringify(data);
	console.log("send message json "+ value);
	request.send(value);
}

/*
 * group update style of message
 */
function setStyle(object, name, value) {
	var attr = name + ':' + value;
	object.setAttribute('style', attr);
}

function getTime() {
	var date = new Date();
	return date.toLocaleTimeString();
}

function changeFontFamily() {
	console.log(selectFont.value);
	fontFamily = selectFont.value;
	pMessageArea.style.fontFamily = fontFamily;
}

function changeFontSize() {
	console.log(selectFontSize.value);
	fontSize = selectFontSize.value;
	pMessageArea.style.fontSize = fontSize;
}

function changeColor() {
	console.log(selectColor.value);
	selectColor.color.hidePicker();
	var value = selectColor.value;
	fontColor = value;
	pMessageArea.style.color = value;
}


/*
 * group login function
 */
function login(loginSuccess){
	var username = inputUsername.value;
	var password = md5(inputPassword.value);
	//var password = inputPassword.value;
	var data = null;
	if(username != null && password != null){
		data = {
			//id : null,
			username : username,
			password : password
			//avatar : null
		};
		//var request = new XmlHttpRequest();
		var request = new XMLHttpRequest();
		request.onreadystatechange = function() {
			if (request.readyState == 4) { // If the request is finished
				if (request.status == 200){ // If it was successful
					console.log("post user success");
					var account = JSON.parse(request.responseText);
					loginSuccess(account);
					hideError();	
				}
				if(request.status == 601){
					showError('Wrong username or password');
				}
				if(request.status == 600){
					showError('User already online');
				}
			}
		};
		request.open("POST", URL_USER);
		request.setRequestHeader("Content-Type","application/json;charset=UTF-8");
		var value = JSON.stringify(data);
		request.send(value);
	}	
}

function showError(error){
	lblError.innerHTML = error;
	lblError.style.visibility = 'visible';
}

function hideError(){
	lblError.style.visibility = 'hidden';
}

function loginSuccess(account){
	username = account.username;
	imgAvatar.src = account.avatar;
	loginForm.style.visibility = 'hidden';
	chatForm.style.visibility = 'visible';
	poll(updateChatArea);
	// interval
	/*timerGetMessage = setInterval(function() {
		checkListMessages(getListMessages);
	}, 1000);
	timerGetUserOnline = setInterval(function() {
		checkListUserOnline(updateRoomInfo);
	}, 3333);*/
	//timerRequest = setInterval(checkListMessages(getListMessages), 1000);
}

function enterForLogin(event) {
	if(event.keyCode == 13)
		login(loginSuccess);
}
/*
 * group list user online function
 */
function checkListUserOnline(updateRoomInfo){
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4) { // If the request is finished
			if (request.status == 200){// If it was successful
				var bodyResponse = request.responseText;
				var listUserOnline = JSON.parse(bodyResponse);
				updateRoomInfo(listUserOnline);
				
			} 
				
		}
	};
	request.open("GET", URL_USER);
	request.send(null);
}

function updateRoomInfo(listUserOnline){
	roomInfoArea.innerHTML = '';
	for ( var i = 0; i < listUserOnline.length; i++) {		
		var user = listUserOnline[i];
		var p = document.createElement('p');
		p.className = 'user-info';
		var img = document.createElement('img');
		img.src = user.avatar;
		var spanAvatar = document.createElement('span');
		spanAvatar.appendChild(img);
		var spanName = document.createElement('span');
		spanName.innerHTML = user.username;		
		p.appendChild(spanAvatar);
		p.appendChild(spanName);
		roomInfoArea.appendChild(p);
	}	
}
/*
 * group quit function
 */
function quit(){
	var data={username:username};
	post(URL_USER,data);
}